<template>
  <div class="home">
    <van-nav-bar title="购物袋" left-arrow>
      <template #left>
        <Back></Back>
      </template>
      <template #right>
        <div
          v-if="shopMessage.length === 0 ? false : true"
          @click="goDelete"
          v-text="isDelete ? '完成' : '编辑'"
        ></div>
      </template>
    </van-nav-bar>
    <div class="shopbag-img">
      <img class="head-img" src="../assets/images/shopbag_bg.png" alt="" />
    </div>
    <van-checkbox-group v-model="result" ref="checkboxGroup">
      <van-swipe-cell v-for="(v, i) in shopMessage" :key="i">
        <div class="check-box">
          <van-checkbox :name="i" @click="isCheckAll" />
        </div>
        <van-card
          :price="v.price"
          :desc="v.enname"
          :title="v.name"
          :thumb="v.small_img"
          @click-thumb="goShopMes(i)"
        >
          <template #tags>
            <div class="shop-rule">{{ v.rule }}</div>
          </template>
          <template #footer>
            <van-button
              size="mini"
              @click="reduce(i)"
              :class="v.count > 1 ? 'allow' : ''"
              >-</van-button
            >
            <span class="shop-num">{{ v.count }}</span>
            <van-button
              size="mini"
              @click="add(i)"
              :class="v.count < 99 ? 'allow' : ''"
              >+</van-button
            >
          </template>
        </van-card>
        <template #right>
          <van-button
            square
            text="删除"
            type="danger"
            class="delete-button"
            @click="deleteOne(i)"
          />
        </template>
      </van-swipe-cell>
    </van-checkbox-group>

    <van-empty
      description="购物车空空如也"
      v-show="shopMessage.length === 0 ? true : false"
    >
      <van-button round type="danger" class="bottom-button" @click="goMenu">{{
        !tokenString ? "去登录" : "去菜单看看"
      }}</van-button>
    </van-empty>

    <div v-if="shopMessage.length === 0 ? false : true">
      <div v-show="!isDelete">
        <van-submit-bar
          :price="total"
          button-text="提交订单"
          button-color="rgb(12,52,186)"
          @submit="goOrderSet"
        >
          <van-checkbox v-model="checked" @click="checkAll">全选</van-checkbox>
        </van-submit-bar>
      </div>

      <div v-show="isDelete">
        <van-submit-bar
          button-text="删除选择"
          button-color="rgb(238,10,36)"
          @submit="deleteChecked"
        >
          <van-checkbox v-model="checked" @click="checkAll">全选</van-checkbox>
        </van-submit-bar>
      </div>
    </div>
  </div>
</template>

<script>
import Back from "../components/Back.vue";
import { Toast } from "vant";
export default {
  name: "Shopbag",
  data() {
    return {
      shopMessage: [],
      appkey: "U2FsdGVkX19WSQ59Cg+Fj9jNZPxRC5y0xB1iV06BeNA=",
      tokenString: sessionStorage.getItem("userToken"),
      result: [],
      checked: false,
      total: 0,
      isDelete: false,
    };
  },
  methods: {
    reduce(i) {
      if (this.shopMessage[i].count > 1) {
        this.shopMessage[i].count--;
        this.priceCount();
      }
    },
    add(i) {
      if (this.shopMessage[i].count < 99) {
        this.shopMessage[i].count++;
        this.priceCount();
      }
    },
    getShopMessage(n = null) {
      if (n) {
        var num = Number(n);
      }
      let tokenString = this.tokenString;
      if (!tokenString) {
        return;
      }
      let appkey = this.appkey;
      this.axios({
        method: "get",
        url: "http://www.kangliuyong.com:10002/findAllShopcart",
        params: {
          appkey,
          tokenString,
        },
      })
        .then((res) => {
          this.shopMessage = res.data.result;
          for (let j = 0; j < this.result.length; j++) {
            if (this.result[j] === num) {
              this.result.splice(j, 1);
              j--;
            }
            if (this.result[j] > num) {
              this.result[j]--;
            }
          }
          let result = JSON.parse(JSON.stringify(this.result));
          this.result = result;

          this.priceCount();
          this.isCheckAll();
        })
        .catch((err) => {});
    },
    checkAll() {
      if (this.checked) {
        this.$refs.checkboxGroup.toggleAll(true);
      } else {
        this.$refs.checkboxGroup.toggleAll(false);
      }
      this.priceCount();
    },
    isCheckAll() {
      if (this.result.length < this.shopMessage.length) {
        this.checked = false;
      } else {
        this.checked = true;
        if (this.shopMessage.length === 0) {
          this.checked = false;
        }
      }
      this.priceCount();
    },
    priceCount() {
      let total = 0;
      this.result.forEach((v) => {
        total += this.shopMessage[v].price * this.shopMessage[v].count;
      });
      this.total = total * 100;
    },
    goDelete() {
      this.isDelete = !this.isDelete;
    },
    deleteChecked() {
      let tokenString = this.tokenString;
      let appkey = this.appkey;
      let sids = [];
      for (let i = 0; i < this.result.length; i++) {
        sids.push(this.shopMessage[this.result[i]].sid);
      }
      sids = JSON.stringify(sids);
      this.result = [];
      this.checked = false;
      this.priceCount();
      let data = `appkey=${appkey}&sids=${sids}&tokenString=${tokenString}`;
      this.axios({
        method: "post",
        url: "http://www.kangliuyong.com:10002/deleteShopcart",
        data,
      })
        .then((res) => {
          this.getShopMessage();
        })
        .catch((err) => {});
    },
    deleteOne(i) {
      let index = String(i);
      let tokenString = this.tokenString;
      let appkey = this.appkey;
      let sids = [];
      sids.push(this.shopMessage[index].sid);
      sids = JSON.stringify(sids);
      let data = `appkey=${appkey}&sids=${sids}&tokenString=${tokenString}`;
      this.axios({
        method: "post",
        url: "http://www.kangliuyong.com:10002/deleteShopcart",
        data,
      })
        .then((res) => {
          this.getShopMessage(index);
          Toast.success("删除成功");
        })
        .catch((err) => {});
    },
    goShopMes(i) {
      let pid = this.shopMessage[i].pid;

      this.$router.push({ name: "ShopMes", query: { pid } });
    },
    goOrderSet() {
      let sids = [];
      for (let i = 0; i < this.result.length; i++) {
        sids.push(this.shopMessage[this.result[i]].sid);
      }
      if (sids.length > 0) {
        sids = JSON.stringify(sids);
        this.$router.push({
          name: "OrderSet",
          query: { sids },
        });
      } else {
        Toast.fail("请添加商品");
      }
    },
    goMenu() {
      let tokenString = this.tokenString;
      if (!tokenString) {
        this.goLogin();
      } else {
        this.$router.push({ name: "Menu" });
      }
    },
    goLogin() {
      this.$router.push({ name: "Login" });
    },
  },
  created() {
    this.getShopMessage();
  },
  components: {
    Back,
  },
  beforeRouteLeave(to, from, next) {
    if (this.shopMessage.length > 0) {
      let tokenString = this.tokenString;
      let appkey = this.appkey;
      let sid = "";
      let count = 0;
      let data = "";
      this.shopMessage.forEach((v) => {
        sid = v.sid;
        count = v.count;
        data = `appkey=${appkey}&sid=${sid}&tokenString=${tokenString}&count=${count}`;

        this.axios({
          method: "post",
          url: "http://www.kangliuyong.com:10002/modifyShopcartCount",
          data,
        })
          .then((res) => {
            // Toast("商品配置已自动保存");
            next();
          })
          .catch((err) => {});
      });
    } else {
      next();
    }
  },
};
</script>

<style lang="less" scoped>
.home {
  padding-bottom: 110px;
}
.shopbag-img {
  width: 100%;
  img {
    width: 100%;
  }
}

.delete-button {
  height: 100%;
}
/deep/.van-card__footer {
  position: absolute;
  right: 16px;
  bottom: 8px;
  width: 80px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
/deep/ .van-button--mini {
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  border-radius: 50%;
  background-color: #ddd;
  border: 1px solid #bbb;
  font-size: 18px;
}
.shop-num {
  font-size: 16px;
}
.allow {
  background-color: rgb(12, 52, 186);
  color: #fff;
}
/deep/.van-card {
  padding-left: 40px;
}
.check-box {
  position: absolute;
  left: 10px;
  top: 42px;
  // background-color: red;
  z-index: 9;
}
/deep/.van-submit-bar {
  bottom: 50px;
  border-bottom: 1px solid #eee;
}
/deep/.van-submit-bar__bar {
  justify-content: space-between;
}
/deep/.van-nav-bar {
  position: sticky;
  top: 0;
}
/deep/.van-card__title {
  font-size: 14px;
}
/deep/.van-card__desc {
  color: #999;
}
.shop-rule {
  color: #aaa;
}
.bottom-button {
  background-color: rgb(12, 52, 186);
  border: 1px solid rgb(12, 52, 186);
}
/deep/.van-swipe-cell__wrapper {
  position: relative;
}
</style>